package io.renren.modules.sp.controller;

import com.alibaba.excel.util.StringUtils;
import io.renren.common.annotation.LogOperation;
import io.renren.modules.sp.service.SpBaseMatchItemService;
import io.renren.modules.sp.service.SpMatchItemService;
import io.renren.modules.sp.service.SpMatchItemTeamUserService;
import io.renren.modules.sp.service.SpMatchService;
import io.swagger.annotations.Api;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColumns;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STSectionMark;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static java.lang.System.out;
/**
 * 报表
 * @date 2023-04-21
 */
@RestController
@RequestMapping("/sp/spmatchReport")
@Api(tags="报表")
public class SpMatchReportController {
    @Autowired
    SpMatchItemTeamUserService spMatchItemTeamUserService;
    @Autowired
    SpMatchService matchService;
    @Autowired
    SpMatchItemService spMatchItemService;
    @Autowired
    SpBaseMatchItemService spBaseMatchItemService;




    /**
     * 导出1
     * */
    @RequestMapping("/export")
    @LogOperation("导出")
    public void export(HttpServletResponse response,String myMatchId,String mygroupId,String myprovince,String mymatchItemId
    ,String type ) throws Exception {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 添加工作表
        Sheet sheet = workbook.createSheet("Sheet1");
        String fileName = "00.xlsx";

        if ("1".equals(type)) {
            //查询数据
            List<Map<String, String>> dataTable = spMatchItemTeamUserService.queryReport(myMatchId, mygroupId, myprovince, mymatchItemId, type);
            List<String> topNameList = new ArrayList<>();
            List<String> typeNameList = new ArrayList<>();
            Map<String, Map<String, String>> dataMap = new HashMap<>();
            for (Map<String, String> map : dataTable) {
                if (!topNameList.contains(map.get("topName"))) {
                    topNameList.add(map.get("topName"));
                }
                if (!typeNameList.contains(map.get("typeName"))) {
                    typeNameList.add(map.get("typeName"));
                }
                dataMap.put(map.get("topName") + "-" + map.get("typeName"), map);
            }
            //通义灵码写的代码，有bug和我没关系
            for (int i = 0; i < typeNameList.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Cell cell = row.createCell(0);
                cell.setCellValue(typeNameList.get(i));
                for (int j = 0; j < topNameList.size(); j++) {
                    Cell cell1 = row.createCell(j + 1);
                    Map<String, String> item = dataMap.get(topNameList.get(j) + "-" + typeNameList.get(i));
                    if (item != null) {
                        if (item.get("num") != null) {
                            cell1.setCellValue(item.get("num"));
                        } else {
                            cell1.setCellValue("0");
                        }
                    }
                }
            }
            Row row = sheet.createRow(0);
            for (int j = 0; j < topNameList.size(); j++) {
                Cell cell1 = row.createCell(j + 1);
                cell1.setCellValue(topNameList.get(j));
            }
            String matchName = matchService.selectById(Long.parseLong(myMatchId)).getMatchName();
            int pNum = topNameList.size();
            int iNum = topNameList.size();
            fileName = String.format("省份-赛项-%s-%s-%s", matchName, pNum, iNum);
        } else {

            //查询数据
            List<Map<String, String>> dataTable = spMatchItemTeamUserService.queryReport(myMatchId, mygroupId, myprovince, mymatchItemId, type);
            List<String> topNameList = new ArrayList<>();
            List<String> typeNameList = new ArrayList<>();
            Map<String, Map<String, String>> dataMap = new HashMap<>();
            for (Map<String, String> map : dataTable) {
                if (!topNameList.contains(map.get("topName"))) {
                    topNameList.add(map.get("topName"));
                }
                String typeName = map.get("typeName");
                typeName = typeName + "@@" + map.get("groupName");
                if (!typeNameList.contains(typeName)) {
                    typeNameList.add(typeName);
                }
                dataMap.put(map.get("topName") + "-" + typeName, map);
            }

            for (int i = 0; i < typeNameList.size(); i++) {
                Row row = sheet.createRow(i + 1);
                String typeName = typeNameList.get(i);
                String[] typeNameArr = typeName.split("@@");
                Cell cell = row.createCell(0);
                Cell cellG = row.createCell(1);
                cell.setCellValue(typeNameArr[0]);
                cellG.setCellValue(typeNameArr[1]);
                for (int j = 0; j < topNameList.size(); j++) {
                    Cell cell1 = row.createCell(j + 2);
                    Map<String, String> item = dataMap.get(topNameList.get(j) + "-" + typeNameList.get(i));
                    if (item != null) {
                        if (item.get("num") != null) {
                            cell1.setCellValue(item.get("num"));
                        } else {
                            cell1.setCellValue("0");
                        }
                    }
                }
            }
            Row row = sheet.createRow(0);
            for (int j = 0; j < topNameList.size(); j++) {
                Cell cell1 = row.createCell(j + 2);
                cell1.setCellValue(topNameList.get(j));
            }

            // “赛组省-A-B-C-D”，A为选择的赛事名，B为选择的赛项名称，C为选择的组别数量，D为选择的省份的数量

            String matchName = matchService.selectById(Long.parseLong(myMatchId)).getMatchName();

            String itemName = "全部";
            if (StringUtils.isNotBlank(mymatchItemId)) {
                itemName = spBaseMatchItemService.selectById(spMatchItemService.selectById(Long.parseLong(mymatchItemId.split(",")[0]))
                        .getBaseMatchItemId()
                ).getItemName();
            }
            int pNum = topNameList.size();
            int iNum = topNameList.size();
            fileName = String.format("赛组省-%s-%s-%s-%s", matchName, itemName, iNum, pNum);
        }

        //中文转换
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //设置文件名称
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //设置响应类型
        response.setContentType("application/vnd.ms-excel");
        workbook.write(response.getOutputStream());
        out.close();
        //关闭流
        workbook.close();
    }


    /**
     * 导出1
     * */
    @RequestMapping("/exportSign")
    public void exportSign(HttpServletResponse response,String matchName ,Long matchLevel,String beginSignup ,String endSignup
    ,Long province,Long city) throws Exception {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 添加工作表
        Sheet sheet = workbook.createSheet("Sheet1");
        String fileName = "我要分的更高.xlsx";
        //查询数据
        List<Map<String, String>> dataTable  = spMatchItemTeamUserService.querySignReport( matchName , matchLevel, beginSignup , endSignup , province, city);
        List<String> topNameList = new ArrayList<>();
        List<String> typeNameList = new ArrayList<>();
        Map<String,Map<String,String>> dataMap = new HashMap<>();
        for(Map<String,String> map : dataTable){
            if(!topNameList.contains(map.get("topName"))){
                topNameList.add(map.get("topName"));
            }
            if(!typeNameList.contains(map.get("typeName"))){
                typeNameList.add(map.get("typeName"));
            }
            dataMap.put(map.get("topName")+"-"+map.get("typeName"),map);
        }
        //通义灵码写的代码，有bug和我没关系
        for(int i = 0 ; i < typeNameList.size() ; i++){
            Row row = sheet.createRow(i+1);
            Cell cell = row.createCell(1);
            cell.setCellValue(typeNameList.get(i));
            Cell cellIndex = row.createCell(0);
            cellIndex.setCellValue(String.format("%03d", i+1));
            for(int j = 0 ; j < topNameList.size() ; j++){
                Cell cell1 = row.createCell(j+2);
                Map<String,String> item = dataMap.get(topNameList.get(j)+"-"+typeNameList.get(i));
                if(item !=null ){
                    if(item.get("num")!=null){
                        cell1.setCellValue(item.get("num"));
                    }else{
                        cell1.setCellValue("0");
                    }
                }else{
                    cell1.setCellValue("0");
                }
            }
        }
        Row row = sheet.createRow(0);
        for(int j = 0 ; j < topNameList.size() ; j++){
            Cell cell1 = row.createCell(j+2);
            cell1.setCellValue(topNameList.get(j));
        }
        fileName = "赛事成功报名数量.xlsx";
        //中文转换
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //设置文件名称
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //设置响应类型
        response.setContentType("application/vnd.ms-excel");
        workbook.write(response.getOutputStream());
        out.close();
        //关闭流
        workbook.close();
    }

    /**
     * 导出1
     * */
    @RequestMapping("/exportSignWord")
    public void exportSignWord(HttpServletResponse response,Long matchId,String items  ) throws Exception {
        XWPFDocument document = new XWPFDocument();
        List<Long> itemsList = null;
        if(StringUtils.isNotBlank(items)){
            itemsList = Arrays.asList(items.split(",")).stream().map(Long::parseLong).collect(Collectors.toList());
        }
        List<Map<String,String>> list =  spMatchItemTeamUserService.queryTicketByMatch(matchId,itemsList);
        //bsm.item_name ,g.dict_label,u.real_name,st.ticket
        String groupName = "";
        String title ="";
        XWPFTable table = null;
        List<String> rows = new ArrayList<>();
        for(Map<String,String> item  : list){
            String currentGroup = String.format("%s  %s",item.get("item_name"),item.get("dict_label"));
            String currentTitle =item.get("item_name");
            if(StringUtils.isBlank(groupName)||!currentGroup.equals(groupName)){
                if(rows.size()>0){
                    WordUtil.addTableRow(table,rows.toArray(new String[]{}));
                    rows.clear();
                }
                groupName = currentGroup;



                if(StringUtils.isBlank(title)||!currentTitle.equals(title))
                {
                    title = currentTitle;
                    XWPFParagraph titlteP = document.createParagraph();
                    //titlteP.setAlignment(ParagraphAlignment.CENTER);
                    XWPFRun runt = titlteP.createRun();
                    runt.setFontFamily("仿宋");
                    //4号字体的字号约为 14 磅 小4号字体的字号约为 14 磅
                    runt.setFontSize(14);
                    runt.setBold(true);
                    runt.setText(currentTitle);
                }
                XWPFParagraph paraBreak = document.createParagraph();

                XWPFRun run = paraBreak.createRun();
                run.setText(groupName);
                // 设置为仿宋字体，具体可根据系统字体设置
                run.setFontFamily("仿宋");
                run.setBold(true);
                //4号字体的字号约为 14 磅 小4号字体的字号约为 14 磅
                run.setFontSize(12);
                CTSectPr sectPr2 = paraBreak.getCTP().addNewPPr().addNewSectPr();
                sectPr2.addNewType().setVal(STSectionMark.CONTINUOUS);
                CTColumns columns = sectPr2.addNewCols();
                columns.setNum(BigInteger.valueOf(1));  // 设置为三栏
                columns.setSpace(BigInteger.valueOf(720));  // 栏间距为720




                table=WordUtil.addTable(document,new String[]{"姓名","参赛编号"});
                XWPFParagraph tableP = document.createParagraph();
                XWPFRun run2 = paraBreak.createRun();
                CTSectPr sectPr = tableP.getCTP().addNewPPr().addNewSectPr();
                sectPr.addNewType().setVal(STSectionMark.CONTINUOUS);
                CTColumns columns1 = sectPr.addNewCols();
                columns1.setNum(BigInteger.valueOf(3));  // 设置为三栏
                columns1.setSpace(BigInteger.valueOf(720));  // 栏间距为720
               // XWPFParagraph paraBreak1 = document.createParagraph();
               // paraBreak.createRun().addBreak(BreakType.COLUMN);


              //  table.setLeftBorder(XWPFTable.XWPFBorderType.NONE , (short)24,1,"rgb(0,0,0)");
                // 插入连续分节符

                WordUtil.setRepeatHeaderRow(table);
            }
            rows.add(item.get("real_name"));
            String st = item.get("ticket");
            st = st.replace("07A","");
            rows.add(st);
            if(rows.size()==2){
                WordUtil.addTableRow(table,rows.toArray(new String[]{}));
                rows.clear();
            }
        }
        if(rows.size()>0){
            WordUtil.addTableRow(table,rows.toArray(new String[]{}));
            rows.clear();
        }
        String  fileName = "赛事报名名单.docx";
        //中文转换
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //设置文件名称
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //设置响应类型
        response.setContentType("application/vnd.ms-excel");
        document.write(response.getOutputStream());
        out.close();
        //关闭流
        document.close();
    }
}
